from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker

from commons.entity.po.advance_approval import AdvanceApproval
from commons.mappers.base_mapper import BaseMapper

# 创建数据库引擎
db_url = "mysql+pymysql://root:123456@localhost/ctdb"
engine = create_engine(db_url, echo=True)

# 创建会话类
Session = sessionmaker(bind=engine)


class AdvanceApprovalMapper(BaseMapper):
    def __init__(self):
        super().__init__(Session)

    def select_by_advance_approval_id(self, advance_approval_id):
        """
        根据 advance_approval_id 从数据库获取 AdvanceApproval 对象
        :param advance_approval_id: str
        :return: AdvanceApproval 对象或 None
        """
        try:
            with self.session_factory() as session:
                advance_approval = session.query(AdvanceApproval).filter_by(
                    advance_approval_id=advance_approval_id).first()
                if advance_approval:
                    return advance_approval
                return None
        except SQLAlchemyError as e:
            print(f"Database error: {str(e)}")
            return None

    def delete_by_advance_approval_id(self, advance_approval_id):
        """
        根据 advance_approval_id 删除审批预支款申请记录
        :param advance_approval_id: str
        :return: True（删除成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                advance_approval = session.query(AdvanceApproval).filter_by(
                    advance_approval_id=advance_approval_id).first()
                if advance_approval:
                    session.delete(advance_approval)
                    session.commit()  # 提交事务
                    return True
                return False  # 记录不存在
        except SQLAlchemyError as e:
            print(f"Database error during delete operation: {str(e)}")
            return False

    def update_by_advance_approval_id(self, advance_approval_update, advance_approval_id):
        """
        根据 advance_approval_id 更新审批预支款申请记录
        :param advance_approval_id: str
        :param advance_approval_update: AdvanceApproval 类实例或字典，包含需要更新的字段
        :return: True（更新成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                advance_approval = session.query(AdvanceApproval).filter_by(
                    advance_approval_id=advance_approval_id).first()
                if advance_approval:
                    # 如果 advance_approval_update 是类实例，转换为字典
                    if advance_approval_update and hasattr(advance_approval_update, 'to_dict'):
                        advance_approval_update = advance_approval_update.to_dict()

                    # 使用新数据更新记录属性
                    for key, value in advance_approval_update.items():
                        if value is not None and hasattr(advance_approval, key):
                            setattr(advance_approval, key, value)

                    session.commit()  # 提交事务
                    return True
                return False  # 记录不存在
        except SQLAlchemyError as e:
            print(f"Database error during update operation: {str(e)}")
            return False

    def select_by_advance_travel_id(self, travel_id):
        """
        根据 travel_id 从数据库获取 AdvanceApproval 对象
        :param travel_id: str
        :return: AdvanceApproval 对象或 None
        """
        try:
            with self.session_factory() as session:
                advance_approval = session.query(AdvanceApproval).filter_by(
                    travel_id=travel_id).first()
                if advance_approval:
                    return advance_approval
                return None
        except SQLAlchemyError as e:
            print(f"Database error: {str(e)}")
            return None